package com.ck.ips.controller;

import com.ck.core.annotation.LoginRequired;
import com.ck.core.constant.PageConstant;
import com.ck.core.export.util.SimpleExportUtil;
import com.ck.core.util.DateUtils;
import com.ck.core.util.ExportUtil;
import com.ck.ips.model.vo.DeviceProgramInfoVO;
import com.ck.ips.model.vo.PlayLogVO;
import com.ck.ips.model.vo.SevenNotLoginDeviceVO;
import com.ck.ips.model.vo.device.DeviceBasicInfoVO;
import com.ck.ips.service.DeviceService;
import com.ck.ips.service.report.ReportFormsService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 报表controller
 * @author: zhanglei
 * @date: 2019/5/10 10:40
 */
@LoginRequired
@Controller
@RequestMapping(value = "/reportForms")
public class ReportFormsController {

    private Logger logger = LoggerFactory.getLogger(ReportFormsController.class);

    @Autowired
    private ReportFormsService reportFormsService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    ExportUtil exportUtil;

    /**
     * 今日终端信息数据统计
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getToDayDeviceInfo")
    public Object getToDayDeviceInfo(){
        return reportFormsService.getToDayDeviceInfo();
    }

    /**
     * 今日节目信息统计数据
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getToDayProgramInfo")
    public Object getToDayProgramInfo(){
        return reportFormsService.getToDayProgramInfo();
    }

    /**
     * 新ui首页今日节目和素材发布信息（含自营和api）
     */
    @ResponseBody
    @RequestMapping(value = "/getNewToDayProgramInfo")
    public Object getNewToDayProgramInfo(){
        return reportFormsService.getNewToDayProgramInfo();
    }

    /**
     * 今日异常统计
     */
    @ResponseBody
    @RequestMapping(value = "/getStatistics")
    public Object getStatistics(){
        return reportFormsService.getStatistics();
    }

    /**
     * 7日未上线终端详情
     */
    @ResponseBody
    @RequestMapping(value = "/sevenNotLoginDeviceInfo")
    public Object sevenNotLoginDeviceInfo(Integer pageNum,Integer pageSize,String startTime){
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        return reportFormsService.sevenNotLoginDeviceInfo(pageNum,pageSize,startTime);
    }

    /**
     * 查看增播减播下发失败的详情
     */
    @ResponseBody
    @RequestMapping(value = "/programAddSubFailedInfo")
    public Object programAddSubFailedInfo(Integer pageNum,Integer pageSize){
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        //增播减播下发失败统一查询
        return reportFormsService.addSubFailedInfo(pageNum,pageSize);
    }

    /**
     * 近七天终端上线离线状态
     */
    @ResponseBody
    @RequestMapping(value = "/sevenDeviceLineInfo")
    public Object sevenDeviceLineInfo(){
        return reportFormsService.sevenDeviceLineInfo();
    }

    /**
     * 近七天节目发布信息数
     */
    @ResponseBody
    @RequestMapping(value = "/sevenProgramInfo")
    public Object sevenProgramInfo(){
        return reportFormsService.sevenProgramInfo();
    }

    /**
     * 近七天单个素材平均每天曝光次数
     */
    @ResponseBody
    @RequestMapping(value = "/fileAverageExposureNum")
    public Object fileAverageExposureNum(){
        //曝光次数
        return reportFormsService.fileAverageExposureNum();
    }

    /**
     * 近7天单个节目平均每天曝光次数
     */
    @ResponseBody
    @RequestMapping(value = "/programAverageExposureNum")
    public Object programAverageExposureNum(String programVersion){
        //曝光次数
        return reportFormsService.programAverageExposureNum(programVersion);
    }

    /**
     * 近七天已下发的单个终端下载素材量
     */
    @ResponseBody
    @RequestMapping(value = "/getFileDownloadNun")
    public Object getFileDownloadNun(){
        //单个终端下载素材量
        return reportFormsService.getFileDownloadNun();
    }

    /**
     * 近7天单个终端节目下载趋势
     */
    @ResponseBody
    @RequestMapping(value = "/getProgramDownloadNum")
    public Object getProgramDownloadNum(){
        //单个终端下载节目量
        return reportFormsService.getProgramDownloadNum();
    }

    /**
     * 根据设备的deviceCode查询终端上线日志
     * @param dayTime 时间 如：2019-05-23
     * @param deviceCode 终端唯一编码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getOnLineInfo")
    public Object getOnLineInfo(String dayTime,String deviceCode,Integer pageNum,Integer pageSize){
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        return reportFormsService.getOnLineInfo(dayTime,deviceCode,pageNum,pageSize);
    }

    /**
     * 报表统计-播放日志-每日
     * @param deviceCode 终端唯一编码
     * @param dayTime 具体某天时间 如：20190514
     * @param pageNum 当前页
     * @param pageSize 每页条数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/reportLogDay")
    public Object reportLogDay(String deviceCode,String dayTime,Integer pageNum,Integer pageSize){
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        return reportFormsService.reportLogDay(deviceCode,dayTime,pageNum,pageSize);
    }

    /**
     * 报表统计-播放日志-每月
     * @param deviceCode 终端唯一编码
     * @param monthTime 具体某月时间 如：201905
     * @param pageNum 当前页
     * @param pageSize 每页条数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/reportLogMonth")
    public Object reportLogMonth(String deviceCode,String monthTime,Integer pageNum,Integer pageSize){
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        return reportFormsService.reportLogMonth(deviceCode,monthTime,pageNum,pageSize);
    }

    /**
     * 报表统计-播放日志-时段
     * @param deviceCode 终端唯一编码
     * @param dayStartTime 起始时间 如：20190510
     * @param dayEndTime 终止时间 如：20190514
     * @param pageNum 当前页
     * @param pageSize 每页条数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/reportLogTimeFrame")
    public Object reportLogTimeFrame(String deviceCode,String dayStartTime,String dayEndTime,Integer pageNum,Integer pageSize){
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        return reportFormsService.reportLogTimeFrame(deviceCode,dayStartTime,dayEndTime,pageNum,pageSize);
    }

    /**
     * 报表统计-播放日志-时段
     * @param deviceCode 终端唯一编码
     * @param dayStartTime 起始时间 如：2019-05-10
     * @param dayEndTime 终止时间 如：2019-05-14
     * @return excel
     */
    @ResponseBody
    @RequestMapping(value = "/reportLogTimeFrameExcel")
    public void reportLogTimeFrameExcel(HttpServletResponse response,String deviceCode, String dayStartTime, String dayEndTime) throws IOException {
        Long oldDayStartTime = null;
        Long oldDayEndTime = null;
        XSSFWorkbook workbook = null;
        try {
            oldDayStartTime = DateUtils.stringTimeToLongTimeStamp(dayStartTime,DateUtils.PATTEN_YMD);
            oldDayEndTime = DateUtils.stringTimeToLongTimeStamp(dayEndTime,DateUtils.PATTEN_YMD);
            String newDayStartTime =  DateUtils.longTimeStampToStringDate(oldDayStartTime,DateUtils.PATTEN_YYYYMMDD);
            String newEndStartTime =  DateUtils.longTimeStampToStringDate(oldDayEndTime,DateUtils.PATTEN_YYYYMMDD);
            //查询数据
            List<PlayLogVO> playLogVOS = reportFormsService.reportLogTimeFrameExcel(deviceCode,newDayStartTime,newEndStartTime);
            //创建时间
            String playDate = dayStartTime + "至" + dayEndTime;
            //装入excel表中
            workbook = reportFormsService.createLogExcel(playLogVOS,playDate);
            //准备将Excel的输出流通过response输出到页面下载
            //输出流
            response.setContentType("application/ms-excel");
            response.setCharacterEncoding("UTF-8");
            //这后面可以设置导出Excel的名称，此例中名为student.xls
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("播放日志详情.xlsx", "UTF-8"));
            //刷新缓冲
            response.flushBuffer();
            if(null != workbook){
                //workbook将Excel写入到response的输出流中，供页面下载
                workbook.write(response.getOutputStream());
            }
        } catch (Exception e) {
            logger.error("导出报表统计-播放日志-时段(reportLogTimeFrameExcel) 失败：" + e.getMessage(), e);
        } finally {
            if(null != workbook){
                workbook.close();
            }
        }
    }

    /**
     * 今日解绑终端数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/todayUntieDeviceNum")
    public Object todayUntieDeviceNum(){
        return reportFormsService.todayUntieDeviceNum();
    }

    /**
     * 导出七日未上线设备信息
     *
     * @param response
     */
    @ResponseBody
    @GetMapping(value = "/exportSevenNotLoginDeviceInfo")
    public void exportSevenNotLoginDeviceInfo(HttpServletResponse response, String startTime){
        try (OutputStream out = response.getOutputStream()) {
            List<DeviceBasicInfoVO> deviceList  = new ArrayList<>();
            PageInfo<SevenNotLoginDeviceVO> data = (PageInfo<SevenNotLoginDeviceVO>) reportFormsService.sevenNotLoginDeviceInfo(1, 0, startTime).getData();
            List<SevenNotLoginDeviceVO> sevenNotLoginDeviceVOS = data.getList();
            if(CollectionUtils.isNotEmpty(sevenNotLoginDeviceVOS)){
                List<String> deviceCodeList = sevenNotLoginDeviceVOS.stream().map(SevenNotLoginDeviceVO::getDeviceCode).collect(Collectors.toList());
                deviceList = deviceService.listBasicDeviceInfoByPage(1, 0,
                        null, null, null, null, null, null,
                        null, null, null, null, null,
                        null, null, null, deviceCodeList).getList();
            }
            //设置输出类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("七日未上线设备.xls").getBytes(), "ISO-8859-1"));
            SimpleExportUtil.exportToExcel(deviceList, "七日未上线设备").write(out);
        } catch (Exception e) {
            logger.error("StatisticExportController exportCityList 导出七日未上线设备失败：" + e.getMessage(), e);
        }
    }

    /**
     * 今日新增终端信息列表
     */
    @ResponseBody
    @RequestMapping(value = "/listTodayNewDeviceInfo")
    public Object listTodayNewDeviceInfo(Integer pageNum,Integer pageSize){
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        return reportFormsService.listTodayNewDeviceInfo(pageNum,pageSize);
    }

    /**
     * 导出今日新增终端信息
     *
     * @param response
     */
    @ResponseBody
    @GetMapping(value = "/exportTodayNewDeviceInfo")
    public void exportTodayNewDeviceInfo(HttpServletResponse response){
        try (OutputStream out = response.getOutputStream()) {
            List<DeviceBasicInfoVO> deviceList  = new ArrayList<>();
            List<String> deviceCodeList = deviceService.listTodayNewDeviceCode();
            if(CollectionUtils.isNotEmpty(deviceCodeList)){
                deviceList = deviceService.listBasicDeviceInfoByPage(1, null,
                        null, null, null, null, null, null,
                        null, null, null, null, null,
                        null, null, null, deviceCodeList).getList();
            }
            //设置输出类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("今日新增终端.xls").getBytes(), "ISO-8859-1"));
            SimpleExportUtil.exportToExcel(deviceList, "今日新增终端").write(out);
        } catch (Exception e) {
            logger.error("StatisticExportController exportCityList 导出今日新增设备失败：" + e.getMessage(), e);
        }
    }

    /**
     * 当前设备广告数量统计
     */
    @ResponseBody
    @RequestMapping(value = "/deviceProgramInfo")
    public Object deviceProgramInfo(){
        return reportFormsService.deviceProgramInfo();
    }

    /**
     * 查看广告数量统计详情
     */
    @ResponseBody
    @RequestMapping(value = "/deviceProgramDetail")
    public Object deviceProgramDetail(Integer type,Integer pageNum,Integer pageSize){
        pageNum = pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum;
        pageSize = pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize;
        return reportFormsService.deviceProgramDetail(type,pageNum,pageSize);
    }

    /**
     * 导出广告数量统计详情
     */
    @RequestMapping(value = "/deviceProgramExcel")
    public void deviceProgramExcel(Integer type,HttpServletResponse response){
        try (OutputStream out = response.getOutputStream()) {
            List<DeviceProgramInfoVO> voList = reportFormsService.deviceProgramExcel(type);
            //设置输出类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("设备信息.xls").getBytes(), "ISO-8859-1"));
            exportUtil.exportToExcel(voList, "设备信息").write(out);
        } catch (Exception e) {
            logger.error("导出考勤记录异常：" + e.getMessage(), e);
        }
    }



}
